using GameBaseFramework.Base;
using System;
using System.Collections;
using System.Collections.Generic;
using Unity.VisualScripting;
using UnityEditor.TerrainTools;
using UnityEngine;
using UnityEngine.EventSystems;

namespace GameGraphics.HomeWorld
{
    /// <summary>
    /// 鼠标事件枚举
    /// </summary>
    public enum RaycastType
    {
        /// <summary>
        /// 鼠标移动上去
        /// </summary>
        Hovered,
        /// <summary>
        /// 鼠标点击
        /// </summary>
        Selected
    }

    /// <summary>
    /// 六边形操作，用户主要的操作入口
    /// </summary>
    public class HexOperation : MonoBehaviour, IPointerUpHandler, IPointerDownHandler, IPointerClickHandler, IDragHandler
    {
        /// <summary>
        /// 地块引用
        /// </summary>
        public HexGrid _HexGrid;
        /// <summary>
        /// 网格体引用
        /// </summary>
        public HexMesh _HexMesh;

        /// <summary>
        /// 实体名->实体的字典
        /// </summary>
        private Dictionary<string, HexEntity> _EntityDic = new();

        /// <summary>
        /// 选中的地块集合
        /// </summary>
        private List<HexCell> _SelectCells = new();

        /// <summary>
        /// 选中的实体
        /// </summary>
        private HexEntity _SelectEntity;

        /// <summary>
        /// 鼠标移动上去的地块
        /// </summary>
        private HexCell _HoveredCell;

        /// <summary>
        /// 鼠标移动上去的实体
        /// </summary>
        private HexEntity _HoveredEntity;

        /// <summary>
        /// 上一帧的鼠标位置
        /// </summary>
        public Vector3 MousePosition { get; private set; }

        /// <summary>
        /// 更新
        /// </summary>
        void Update()
        {
            HandleMouseMove();
        }

        void Start()
        {
            var Grid = GameObject.Find("HexGrid");
            if (Grid != null )
            {
            }
        }

        /// <summary>
        /// 鼠标按下
        /// </summary>
        /// <param name="eventData"></param>
        public void OnPointerUp(PointerEventData eventData)
        {
            DebugTool.Log("OnPointerUp");
        }

        /// <summary>
        /// 处理鼠标移动
        /// </summary>
        private void HandleMouseMove()
        {
            if (Input.mousePosition != MousePosition)
            {
                //鼠标移动
                MousePosition = Input.mousePosition;
                HandleMouseEvent(RaycastType.Hovered);
            }
        }

        /// <summary>
        /// 处理鼠标事件
        /// 包括鼠标移动和鼠标点击
        /// </summary>
        private void HandleMouseEvent(RaycastType raycastType)
        {
            var RaycastResult = Raycast(MousePosition, "Entity");
            if (RaycastResult != null)
            {
                //命中实体，选择的是实体
                if (_EntityDic.TryGetValue(RaycastResult.Value.transform.name, out var Entity))
                {
                    HandleEntity(Entity, raycastType);
                }
            }
            else
            {
                RaycastResult = Raycast(MousePosition, "Floor");
                if (RaycastResult != null)
                {
                    //命中地块，选择的是地块
                    var HexCell = _HexGrid.GetCell(HexMetrics.FromPosition(RaycastResult.Value.point));
                    if (HexCell != null)
                    {
                        HandleCell(HexCell, raycastType);
                    };
                }
                else
                {
                    //什么都没命中，点了个奇怪的地方
                    if (raycastType == RaycastType.Hovered)
                    {
                        UnHoveredCell();
                    }
                    else
                        UnSelectCells();
                    return;
                }
            }
        }

        /// <summary>
        /// 处理地块的鼠标事件
        /// </summary>
        /// <param name="hexCell"></param>
        private void HandleCell(HexCell hexCell, RaycastType raycastType)
        {
            if (hexCell.BelongEntity != null)
            {
                //地块归属于一个建筑
                HandleEntity(hexCell.BelongEntity, raycastType);
                return;
            }
            //地块不属于任何建筑
            if (raycastType == RaycastType.Hovered)
            {
                //鼠标移上去，上一个被Hovered的地块变成空闲
                if (hexCell.State == CellState.Idle)
                {
                    if (_HoveredCell != null && _HoveredCell != hexCell)
                    {
                        _HoveredCell.State = CellState.Idle;
                        HoverCell(hexCell);
                        _HexGrid.Repaint();
                    }
                    else if (_HoveredCell != hexCell)
                    {
                        HoverCell(hexCell);
                        _HexGrid.Repaint();
                    }
                }
                if (hexCell.State == CellState.Selected)
                {
                    UnHoveredCell();
                    _HexGrid.Repaint();
                }
            }
            if (raycastType == RaycastType.Selected)
            {
                //点击地块，只分这个地块有没有被选中
                if (hexCell.State == CellState.Selected)
                {
                    //这个地块就是上次选中的地块，直接取消选中
                    UnSelectCells();
                    _HexGrid.Repaint();
                }
                else
                {
                    if (_SelectCells != null)
                        UnSelectCells();
                    SelectCell(hexCell);
                    _HexGrid.Repaint();
                }
            }
        }

        /// <summary>
        /// 选中单个地块
        /// </summary>
        /// <param name="hexCell"></param>
        private void SelectCell(HexCell hexCell)
        {
            _SelectCells.Clear();
            hexCell.State = CellState.Selected;
            _SelectCells.Add(hexCell);
            UnHoveredCell();
        }

        /// <summary>
        /// 取消选中地块
        /// </summary>
        private void UnSelectCells()
        {
            foreach (var i in _SelectCells)
            {
                i.State = CellState.Idle;
            }
            _SelectCells.Clear();
            UnHoveredCell();
        }

        /// <summary>
        /// 取消经过地块
        /// </summary>
        private void UnHoveredCell()
        {
            if (_HexGrid == null) return;
            if (_HoveredCell != null) _HoveredCell.State = CellState.Idle;
            _HoveredCell = null;
            _HexGrid.Repaint();
        }

        /// <summary>
        /// 鼠标移动到地块上
        /// </summary>
        /// <param name="hexCell"></param>
        private void HoverCell(HexCell hexCell)
        {
            hexCell.State = CellState.Hovered_Selectable;
            _HoveredCell = hexCell;
        }

        /// <summary>
        /// 处理实体的鼠标事件
        /// </summary>
        /// <param name="entity"></param>
        private void HandleEntity(HexEntity entity, RaycastType raycastType)
        {
            if (_SelectEntity != null)
            {
                //之前已经选中了一个实体
                if (_SelectEntity == entity)
                {

                }
            }
        }

        /// <summary>
        /// 射线检测
        /// </summary>
        /// <param name="position"></param>
        /// <param name="action"></param>
        public static RaycastHit? Raycast(Vector2 position, string raycastLayer)
        {
            var ray = Camera.main.ScreenPointToRay(position);
            var layer = 1 << LayerMask.NameToLayer(raycastLayer);
            if (Physics.Raycast(ray, out var hit, Mathf.Infinity, layer))
            {
                return hit;
            }
            return null;
        }


        /// <summary>
        /// 鼠标按下
        /// </summary>
        /// <param name="eventData"></param>
        public void OnPointerDown(PointerEventData eventData)
        {
            DebugTool.Log("OnPointerDown");
        }

        /// <summary>
        /// 鼠标点击
        /// </summary>
        /// <param name="eventData"></param>
        public void OnPointerClick(PointerEventData eventData)
        {
            //鼠标点击
            DebugTool.Log("OnPointerClick");
            HandleMouseEvent(RaycastType.Selected);
        }

        /// <summary>
        /// 拖动
        /// </summary>
        /// <param name="eventData"></param>
        public void OnDrag(PointerEventData eventData)
        {
            throw new NotImplementedException();
        }
    }

}